import { RouteRecordRaw } from "vue-router"
import { constantRoutes } from "@/router";
import { RouteVO } from "@/api/menu/model"
import MenuAPI from '@/api/menu'
import {store} from '@/store'

const modules = import.meta.glob("../../views/**/**.vue");
import { Layout } from "@/router"


/**
 * 使用meta.role确定当前用户是否具有权限
 * 
 * @param roles 用户角色集合
 * @param route 路由
 * @returns 
 */
const hasPermission = (roles:string[],route:RouteRecordRaw) =>{
    if(route.meta && route.meta.roles){
        //"超级管理员"拥有所有权限，直接忽略校验
        if(roles.includes("ROOT")){
            return true
        }
        return roles.some((role) =>{
            if(Array.isArray(route.meta?.roles) && route.meta?.roles){
                return route.meta.roles.includes(role)
            }
        })
    }
    return false
}


/**
 * 递归过滤有权限的动态路由
 *
 * @param routes 接口返回所有的动态路由
 * @param roles 用户角色集合
 * @returns 返回用户有权限的动态路由
 */
const filterAsyncRoutes = (routes:RouteVO[],roles:string[])=>{
    const asyncRoutes:RouteRecordRaw[] = []
    routes.forEach((route)=>{
        const tmpRoute = {...route} as RouteRecordRaw //深拷贝route对象 避免污染
        if(hasPermission(roles,tmpRoute)){
            //如果是顶级目录，替换为 Layout 组件
            if(tmpRoute.component?.toString() == "Layout"){
                tmpRoute.component = Layout
            }else{
                const component = modules[`../../views/${tmpRoute.component}.vue`]
                if(component){
                    tmpRoute.component = component
                }else{
                    tmpRoute.component = modules['../../views/error-page/404.vue']
                }
            }

            // 如果有子路由的情况下
            if(tmpRoute.children){
                tmpRoute.children = filterAsyncRoutes(route.children,roles)
            }

            asyncRoutes.push(tmpRoute)
        }
    })

    return asyncRoutes
}

export const usePermissionStore = defineStore('permission',()=>{
    //state
    const routes = ref<RouteRecordRaw[]>([])

    //action
    const setRoutes = (newRoutes:RouteRecordRaw[]) => {
        routes.value = constantRoutes.concat(newRoutes)
    }

    /**
     * 生成动态路由
     * 
     * @param roles 用户角色集合
     * @returns
     */
    const generateRoutes = async (roles: string[]): Promise<RouteRecordRaw[]> => {
        try {
            // 接口获取所有路由
            const res = await MenuAPI.getRoutes();
            //过滤有权限的动态路由
            const accessedRoutes = filterAsyncRoutes(res, roles);
            setRoutes(accessedRoutes);
            return accessedRoutes;
        } catch (error) {
            throw error;
        }
    }

    /**
   * 获取与激活的顶部菜单项相关的混合模式左侧菜单集合
   */
  const mixLeftMenus = ref<RouteRecordRaw[]>([]);
  const setMixLeftMenus = (topMenuPath: string) => {
    const matchedItem = routes.value.find((item) => item.path === topMenuPath);
    if (matchedItem && matchedItem.children) {
      mixLeftMenus.value = matchedItem.children;
    }
  }
  return {
    routes,
    setRoutes,
    generateRoutes,
    mixLeftMenus,
    setMixLeftMenus,
  };
})

// 非setup
export const usePermissionStoreHook = () =>{
    return usePermissionStore(store);
  }
  